package com.qiaofang.applet.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.Base64;

/**
 * @author QF2019
 */
@Slf4j
public class CookieUtil {

    /**
     * 获取登陆token
     * @param request
     * @return
     */
    public static String getToken(HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();
        if(cookies == null) {
            log.info("获取token 失败,cookie为空");
            return null;
        }

        for(Cookie cookie : cookies) {
            if(!"userInfo".equals(cookie.getName())) {
                continue;
            }
            JSONObject jsonObject = JSON.parseObject(new String(Base64.getDecoder().decode(cookie.getValue())));
            log.info("获取token 成功,cookie:{}", jsonObject);
            return jsonObject.getString("token");
        }
        return null;
    }
}
